const md5 = require("md5");
const dayjs = require("dayjs");
const { SuccessSend } = require("../utils/response");
const UserModel = require("../models/user");

class UserController {
    static async register(req, res, next) {
        try {
            const find = await UserModel.findOne({
                username: req.body.username
            });
            if (find) {
                return SuccessSend(res, {
                    code: -1,
                    success: false,
                    message: "该用户名已存在"
                });
            }
            const user = await UserModel.create({
                username: req.body.username,
                password: req.body.password,
                avatar: req.body.avatar
            });
            SuccessSend(res, {
                code: 200,
                success: true,
                message: "注册成功",
                data: {
                    _id: user._id,
                    username: user.username,
                    avatar: user.avatar
                }
            });
        } catch (error) {
            next(error);
        }
        res.send({
            username: req.body.username,
            password: req.body.password
        });
    }

    static async login(req, res, next) {
        try {
            const user = await UserModel.findOne({
                username: req.body.username
            }).select("+password +status");
            if (!user) {
                return SuccessSend(res, {
                    code: -1,
                    success: false,
                    message: "该用户不存在"
                });
            }
            if (user.password !== md5(req.body.password)) {
                if (user.status == "1") {
                    return SuccessSend(res, {
                        code: -1,
                        success: false,
                        message: "该用户已被禁用"
                    });
                }
                return SuccessSend(res, {
                    code: -1,
                    success: false,
                    message: "密码错误"
                });
            }
            // 管理员使用session校验 普通用户JWT验证
            if (user.role == "admin") {
                req.session.user = {
                    _id: user._id,
                    username: user.username,
                    avatar: user.avatar,
                    lastLogin: user.lastLogin
                };
            } else {
                // 普通用户JWT验证
            }
            const now = dayjs().format("YYYY/MM/DD HH:mm:ss");
            await UserModel.findByIdAndUpdate(user._id, {
                lastLogin: now
            });
            SuccessSend(res, {
                code: 200,
                success: true,
                message: "登录成功",
                data: {
                    _id: user._id,
                    username: user.username,
                    avatar: user.avatar,
                    lastLogin: now
                }
            });
        } catch (error) {
            next(error);
        }
    }

    static async logout(req, res, next) {
        try {
            req.session.destroy();
            SuccessSend(res, {
                success: true,
                message: "退出成功",
                data: "退出成功"
            });
        } catch (error) {
            next(error);
        }
    }

    static async list(req, res, next) {
        try {
            const { pageno = 1, pagesize = 10 } = req.query;
            const total = await UserModel.countDocuments({});
            const list = await UserModel.find({ role: "user" })
                .skip((pageno - 1) * pagesize)
                .limit(pagesize)
                .select("+status +role +createdAt")
                .sort({ createdAt: -1 })
                .lean();
            return SuccessSend(res, {
                success: true,
                data: {
                    list,
                    pageno,
                    pagesize,
                    total: Math.ceil(total / pagesize)
                }
            });
        } catch (error) {
            next(error);
        }
    }

    static async delete(req, res, next) {
        try {
            const { id } = req.params;
            const user = await UserModel.findOne({
                _id: id,
                role: "user"
            });
            if (!user) {
                return SuccessSend(res, {
                    code: -1,
                    message: "用户不存在"
                });
            }
            await UserModel.findByIdAndDelete(id);
            return SuccessSend(res, {
                success: true,
                data: id,
                message: "删除成功"
            });
        } catch (error) {
            next(error);
        }
    }

    static async detail(req, res, next) {
        try {
            const { id } = req.params;
            const user = await UserModel.findById(id);
            if (!user) {
                return SuccessSend(res, {
                    code: -1,
                    message: "用户不存在"
                });
            }
            if (user.role !== "admin") {
                return SuccessSend(res, {
                    code: -1,
                    message: "用户无权限"
                });
            }
            return SuccessSend(res, {
                success: true,
                message: "获取成功",
                data: {
                    _id: user._id,
                    avatar: user.avatar,
                    username: user.username,
                    lastLogin: user.lastLogin
                }
            });
        } catch (error) {
            next(error);
        }
    }
}

module.exports = UserController;
